import 'package:dio/dio.dart';
import 'package:enjoy_plus/utils/event_bus.dart';
import 'package:enjoy_plus/utils/token.dart';

class NetworkService {
  // 创建Dio实例
  final _dio = Dio();
  // 定义网络请求方法
  NetworkService() {
    // 配置基础地址
    _dio.options.baseUrl = 'https://live-api.itheima.net';
    // 设置连接超时时间
    _dio.options.connectTimeout = const Duration(seconds: 5);
    // 设置接收超时时间
    _dio.options.receiveTimeout = const Duration(seconds: 5);
    // 设置请求头
    _dio.options.headers = {'Content-Type': 'application/json'};
    // 添加请求拦截器、响应拦截器
    _addInterceptors();
  }
  // get请求
  // 路径
  // 参数 queryParameters
  Future get(String url, {Map<String, dynamic>? params}) async {
    try {
      final response = await _dio.get(url, queryParameters: params);
      return handleResponse(response);
    } catch (e) {
      return handleError(e);
    }
  }

  // post请求
  // 路径
  // 参数 data
  Future post(String url, dynamic data) async {
    try {
      final response = await _dio.post(url, data: data);
      return handleResponse(response);
    } catch (e) {
      return handleError(e);
    }
  }

  // delete 请求方法
  Future delete(String url) async {
    try {
      final response = await _dio.delete(url);
      return handleResponse(response);
    } catch (e) {
      return handleError(e);
    }
  }

  // 拦截器
  void _addInterceptors() {
    _dio.interceptors.add(InterceptorsWrapper(
      onRequest:
          (RequestOptions options, RequestInterceptorHandler handler) async {
        // 请求拦截器：添加公共请求参数、token 等
        // todo
        final token = TokenManager().getToken() ?? '';
        if (token.isNotEmpty) {
          options.headers['Authorization'] = 'Bearer $token';
        }
        return handler.next(options);
      },
      onResponse: (Response response, ResponseInterceptorHandler handler) {
        // 响应拦截器：统一处理成功响应
        return handler.next(response);
      },
      onError: (DioException error, handler) {
        // 响应拦截器：统一处理错误响应
        return handler.next(error);
      },
    ));
  }

  // 统一处理成功响应
  handleResponse(Response response) {
    if (response.statusCode! >= 200 || response.statusCode! < 300) {
      return response.data;
    } else {
      throw Exception('网络请求失败，状态码：${response.statusCode}');
    }
  }

  // 统一处理错误响应
  handleError(error) {
    if (error is DioException) {
      try {
        if (error.type == DioExceptionType.connectionTimeout ||
            error.type == DioExceptionType.receiveTimeout) {
          throw Exception('网络连接超时，请检查网络设置');
        } else if (error.type == DioExceptionType.badResponse) {
          if (error.response?.statusCode == 401) {
            TokenManager().removeToken();
            // 派发事件，跳转到登录页面
            eventBus.fire(Logout());
          } else {
            throw Exception('响应错误');
          }
        } else {
          throw Exception('网络请求错误：$error');
        }
      } catch (e) {
        throw Exception('未知错误：$error');
      }
    }
  }
}

// 导出
final http = NetworkService();
